//
//  LibraryViewController.m
//  彩虹儿歌
//
//  Created by HelloWorld_L on 15/7/2.
//  Copyright (c) 2015年 HelloBaby. All rights reserved.
//

#import "LibraryViewController.h"
#import "MacroHeader.h"
#import "RequestManager.h"
#import "LibraryVCModel.h"
#import "StyledPageControl.h"
#import "LibraryTableVCell.h"
#import <UIImageView+WebCache.h>
#import "ListViewController.h"
@interface LibraryViewController ()<RequestDelegate,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic, retain) RequestManager *request1;//轮播图
@property (nonatomic, retain) NSTimer *timer;
@property (nonatomic, retain) UIImageView *backGroundImgV;
@property (nonatomic, retain) UIScrollView *carouselScrollV;
@property (nonatomic, retain) StyledPageControl *pageControl;
@property (nonatomic, retain) NSMutableArray *carDataSourceArr;

@property (nonatomic, retain) RequestManager *request2;//tableView
@property (nonatomic, retain) NSDictionary *tabInfoDic;
@property (nonatomic, retain) NSMutableArray *tabDataSourceArr;
@property (nonatomic, retain) UITableView *mainTableV;

@property (nonatomic, retain) UIView *footerView;
@property (nonatomic, retain) UIButton *backBtn;

@end

@implementation LibraryViewController

- (void)dealloc
{
    [_request1.delegate release];
    [_request1 release];
    [_timer release];
    [_backGroundImgV release];
    [_carouselScrollV release];
    [_pageControl release];
    [_carDataSourceArr release];
    [_request2.delegate release];
    [_request2 release];
    [_tabInfoDic release];
    [_tabDataSourceArr release];
    [_mainTableV release];
    [_footerView release];
    [_backBtn release];
    [super dealloc];
}

- (void)viewDidLoad { 
    [super viewDidLoad];
    UIImageView *backgroundImgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"xiaohua01"]];
    [self.view addSubview:backgroundImgV];
    
    self.navigationItem.title = self.naviBarItemTitle;
    
    // Do any additional setup after loading the view.
    self.carDataSourceArr = [NSMutableArray array];
    self.tabDataSourceArr = [NSMutableArray array];
    [self requestData1];
    [self requestData2];
    
    [self createMainTablev];
    [self createFooterView];
    
}

//底部的黑色导航条。
- (void)createFooterView
{
    self.footerView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 113, SCREEN_WIDTH, 49)];
    self.footerView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];
    
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backBtn.frame = CGRectMake(20, 15, 20, 20);
    [self.backBtn setBackgroundImage:[UIImage imageNamed:@"zuojiantou16"] forState:UIControlStateNormal];
    [self.backBtn addTarget:self action:@selector(backTo:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.footerView addSubview:self.backBtn];
    [self.view addSubview:self.footerView];
    [self.footerView release];
}

- (void)backTo:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)createMainTablev
{
    
    self.navigationItem.hidesBackButton = YES;
    
    self.mainTableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 60) style:UITableViewStylePlain];
    self.mainTableV.delegate = self;
    self.mainTableV.dataSource = self;
    self.mainTableV.backgroundColor = [UIColor clearColor];
    self.mainTableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    UIView *headerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, SCREEN_HEIGHT)];
    self.mainTableV.tableHeaderView = headerV;
    
    
    [self.mainTableV registerClass:[LibraryTableVCell class] forCellReuseIdentifier:@"cell"];
    
    [headerV release];
    [self.view addSubview:self.mainTableV];
    [self.mainTableV release];
}

- (void)createCarScrolleView//创建轮播图
{
    self.backGroundImgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 4)];
    self.backGroundImgV.image = [UIImage imageNamed:@"188933-12052GH94711.jpg"];
    self.backGroundImgV.layer.cornerRadius = 40;
    self.backGroundImgV.layer.masksToBounds = YES;
    self.backGroundImgV.userInteractionEnabled = YES;
    
    self.carouselScrollV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 4)];
    self.carouselScrollV.contentSize = CGSizeMake(3 * SCREEN_WIDTH , SCREEN_HEIGHT / 4);
    self.carouselScrollV.backgroundColor = [UIColor clearColor];
    self.carouselScrollV.pagingEnabled = YES;
    self.carouselScrollV.bounces = NO;
    self.carouselScrollV.showsHorizontalScrollIndicator = NO;
    self.carouselScrollV.delegate = self;
    
    //设置阴影
    self.carouselScrollV.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.carouselScrollV.layer.shadowOffset = CGSizeMake(0, 0);
    self.carouselScrollV.layer.shadowRadius = 20;
    self.carouselScrollV.layer.shadowOpacity = 3;
    
    
    [self.backGroundImgV addSubview:self.carouselScrollV];

    
    for (int i = 0; i < self.carDataSourceArr.count; i++) {
        LibraryVCModel *model = (LibraryVCModel *)self.carDataSourceArr[i];
        
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 4)];
        
        [imageV sd_setImageWithURL:[NSURL URLWithString:model.recommend_pic]];
        
        [self.carouselScrollV addSubview:imageV];
        [imageV release];
    }
    
    self.pageControl = [[StyledPageControl alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT / 4 - 20, SCREEN_WIDTH, 20)];
    self.pageControl.backgroundColor = [UIColor clearColor];
    self.pageControl.pageControlStyle = PageControlStyleWithPageNumber;
    self.pageControl.numberOfPages = 3;
    
    [self.carouselScrollV release];
    [self.backGroundImgV release];
    [self.pageControl release];
    
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.carouselScrollV) {
        self.pageControl.currentPage = self.carouselScrollV.contentOffset.x / SCREEN_WIDTH;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self addTimer];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self removeTimer];
}

#pragma mark - NSTimer
- (void)addTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)removeTimer
{
    [self.timer invalidate];
}

- (void)nextImage
{

    if (self.pageControl.currentPage == self.carDataSourceArr.count - 1) {
        self.pageControl.currentPage = 0;

        self.carouselScrollV.contentOffset = CGPointMake(self.pageControl.currentPage * SCREEN_WIDTH, 0);
        
    } else {
        
        if ([self.carouselScrollV subviews].count == 4) {//为了安全，避免网速慢图片未加载完全导致奔溃。
            
            CATransform3D rotate1 = CATransform3DMakeRotation(M_PI / 2, 0, 1, 0);//90
            CATransform3D rotate2 = CATransform3DMakeRotation(-(M_PI / 2), 0, 1, 0);//-90
            CATransform3D rotate3 = CATransform3DMakeRotation(0, 0, 1, 0);//0
            
            self.pageControl.currentPage++;
            
            UIView *imageV =  (UIView *)([self.carouselScrollV subviews][self.pageControl.currentPage - 1]);
            UIView *imageV2 =  (UIView *)([self.carouselScrollV subviews][self.pageControl.currentPage]);
            
            imageV.layer.transform = CATransform3DPerspect2(rotate3, CGPointMake(0, 0), 300);
            imageV2.layer.transform = CATransform3DPerspect2(rotate2, CGPointMake(0, 0), 300);
            [UIView animateWithDuration:2 animations:^{
                self.carouselScrollV.contentOffset = CGPointMake(self.pageControl.currentPage * SCREEN_WIDTH, 0);
                
                imageV.layer.transform = CATransform3DPerspect2(rotate1, CGPointMake(0, 0), 300);
                imageV2.layer.transform = CATransform3DPerspect2(rotate3, CGPointMake(0, 0), 300);
                
            } completion:^(BOOL finished) {
                
                imageV.layer.transform = CATransform3DPerspect2(rotate3, CGPointMake(0, 0), -300);
                
            }];
            
        } else {
            
            [self.mainTableV reloadData];
            
        }
    }
}

// 注意这里是函数，MovieHomePageVC里面也写了同样的这种函数，因为函数不分类，所以这里注意不能与MovieHomePageVC里面的函数名重名，否则会报错。
CATransform3D CATransform3DMakePerspective2(CGPoint center, float disZ)
{
    CATransform3D transToCenter = CATransform3DMakeTranslation(-center.x, -center.y, 0);
    CATransform3D transBack = CATransform3DMakeTranslation(center.x, center.y, 0);
    CATransform3D scale = CATransform3DIdentity;
    scale.m34 = -1.0f/disZ;
    return CATransform3DConcat(CATransform3DConcat(transToCenter, scale), transBack);
}

CATransform3D CATransform3DPerspect2(CATransform3D t, CGPoint center, float disZ)
{
    return CATransform3DConcat(t, CATransform3DMakePerspective2(center, disZ));
}

#pragma mark - 请求数据
- (void)requestData1//轮播图
{
    self.request1 = [[RequestManager alloc] initWithRequestURL:[NSString stringWithFormat:@"http://app.beva.com/box-recommend/pl%@/dcios--kwerge--v2.0.json",self.plistId] requestModel:GET parameter:nil];
    self.request1.delegate = self;
    [self.request1 startRequest];
    [self.request1 release];
    
}

- (void)requestData2//tableView
{
    self.request2 = [[RequestManager alloc] initWithRequestURL:[NSString stringWithFormat:@"http://app.beva.com/box-playlistItemData/p46/pl%@/kwerge--v2.0/page1-rp1000-sign5ebe62d22c69fc3c243a4b3093ff62ca.json",self.plistId] requestModel:GET parameter:nil];
    self.request2.delegate = self;
    [self.request2 startRequest];
    [self.request2 release];
    
}

- (void)requestDidFinishWithData:(NSData *)data
{
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
    
    if ([dic[@"data"] isKindOfClass:[NSArray class]]) {
        NSArray *arr = dic[@"data"];
        for (NSDictionary *modelDic in arr) {
            LibraryVCModel *model = [[LibraryVCModel alloc] init];
            [model setValuesForKeysWithDictionary:modelDic];
            [self.carDataSourceArr addObject:model];
            [model release];
        }
        [self createCarScrolleView];
        self.mainTableV.tableHeaderView = self.backGroundImgV;
        [self.mainTableV addSubview:self.pageControl];
        [self addTimer];//避免数据还没请求到就开始走
        
    } else {
        NSDictionary *dataDic = dic[@"data"];
        self.tabInfoDic = dataDic[@"info"];
        NSArray *arr = dataDic[@"playlist"];
        for (NSDictionary *modelDic in arr) {
            LibraryVCModel *model = [[LibraryVCModel alloc] init];
            [model setValuesForKeysWithDictionary:modelDic];
            [self.tabDataSourceArr addObject:model];
            [model release];
        }
    }
    [self.mainTableV reloadData];
}

- (void)requestError:(NSError *)error
{
    NSLog(@"error:%@",error);
}

#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tabDataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LibraryVCModel *model = (LibraryVCModel *)self.tabDataSourceArr[indexPath.row];
    LibraryTableVCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = model;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return SCREEN_WIDTH / 3 + 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    #warning 理解这里的release释放。
    UIView *clearV = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)] autorelease];
    clearV.backgroundColor = [UIColor clearColor];
//    [clearV release];
    return clearV;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ListViewController *listVC = [[ListViewController alloc] init];
    listVC.plistId = [(LibraryVCModel *)self.tabDataSourceArr[indexPath.row] ID];
    listVC.naviBarItemTitle = [(LibraryVCModel *)self.tabDataSourceArr[indexPath.row] name];
    [self.navigationController pushViewController:listVC animated:YES];
    [listVC release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
